//
//  HMAsyncDrawImage.swift
//  iOSWeibo11
//
//  Created by Apple on 16/7/26.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import SDWebImage

class HMAsyncDrawImage: NSObject {
    
    static let sharedAsyncDrawImage: HMAsyncDrawImage = HMAsyncDrawImage()
    
    /// 内存缓存
    private var imageCache: [String: UIImage] = [String: UIImage]()

    /// 异步绘制图片
    func hm_AsyncDrawImage(urlString: String, drawFinish: (image: UIImage) -> ()) {
        
        // 先判断内存是否有图片, key = url, value = image
        if let image = imageCache[urlString] {
            // 内存中有图片,直接返回
//            print("内存中有头像,直接返回: \(urlString)")
            drawFinish(image: image)
            
            return
        }
        
        // 使用SDWebImage获取图片
        // SDWebImgae下载图片功能,先去沙盒中,去网络
        SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlString), options: SDWebImageOptions(rawValue: 0), progress: nil) { (image, error, _, _, _) -> Void in
            
            /*
            ************
            **下载失败***
            ************
            */
            if error != nil {
                let image = UIImage(named: "downloaderror")!
                // 返回下载失败的图片
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    drawFinish(image: image)
                })
                
                return
            }
            
            // 开启子线程异步绘制圆角图片
            dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
                
                let size = image.size
                
                // 上下文大小的rect
                let rect = CGRect(origin: CGPointZero, size: size)
                
                // 开启上下文
                // size 大小
                // 不透明度: ture 表示不透明, false 表示透明
                UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.mainScreen().scale)
                
                // 设置背景颜色
                UIColor.whiteColor().setFill()
                UIRectFill(rect)
                
                // 圆角路径
                let path = UIBezierPath(ovalInRect: rect)
                
                // 让后面绘制的元素在路径里面
                path.addClip()
                
                // 将图片画到矩形里面
                image.drawInRect(rect)
                
                // 获取图片
                let newImage = UIGraphicsGetImageFromCurrentImageContext()
                
                // 结束上下文
                UIGraphicsEndImageContext()
                
                // 返回绘制好得图片
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
//                    print("SD下载,裁剪头像")
                    self.imageCache[urlString] = newImage
                    drawFinish(image: newImage)
                })
            }
        }
    }
}
